<?php
 
namespace app\common\service;
 
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
 
class HttpService
{
    /**
     * GET请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function get($url, $options = [])
    {
        return self::sendRequest($url, 'GET', $options);
    }
 
    /** POST请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function post($url, $options = [], $is_json = true)
    {
        if (isset($options['query'])) {
            if ($is_json) {
                $options['json'] = $options['query'];
            } else{
                $options['form_params'] = $options['query'];
            }
 
            unset($options['query']);
        }
        return self::sendRequest($url, 'POST', $options);
    }
 
    /**
     * PUT请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function put($url, $options = [])
    {
        return self::sendRequest($url, 'PUT', $options);
    }
 
    /**
     * Delete请求
     * @param $url
     * @param array $options
     * @return mixed
     */
    public static function delete($url, $options = [])
    {
        return self::delete($url, $options);
    }
 
    public static function getOptions($params)
    {
        $baseOptions = [
            'connect_timeout' => 10,
            'timeout' => 10,
            'verify' => false,
            'debug' => false,
        ];
        $options = array_merge($baseOptions, $params);
        return $options;
    }
    /**
     * 发起HTTP请求
     * @param $url
     * @param string $method
     * @param array $options
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function sendRequest($url, string $method, array $options = [])
    {
        $options = self::getOptions($options);
        $client = new Client();
        try {
            $request = $client->request($method, $url, $options);
            $body = $request->getBody();
            $contents = $body->getContents();
            $response = json_decode($contents, true);
            return $response;
 
        } catch (ClientException $e) {
            $response = [
                'code'=>$e->getCode(),
                'message'=> $e->getMessage(),
            ];
            echo json_encode($response);exit;
        }
 
    }
}